package com.kalvan.core.exception;


import com.kalvan.core.system.SystemUtil;

import java.text.MessageFormat;

/**
 * 返回码定义基础类
 *
 * @author chenliang
 * @version 2018年03月6日
 * @see ReturnCode
 */
public class ReturnCode {
    private String system;
    private String code;
    private String desc;

    static String regex = "\\{\\d\\}";

    public ReturnCode(String system, String code, String formatDesc) {
        this.system = system;
        this.code = code;
        this.desc = formatDesc;
    }

    public ReturnCode(String code, String formatDesc) {
        this.system = SystemUtil.constants != null ? SystemUtil.constants.getName() : null;
        this.code = code;
        this.desc = formatDesc;
    }

    /**
     * 占位符{}格式化<br>
     * 如 AbstractErrorCode("PARAM_ERROR", "参数错误：{0}msg{1}")
     *
     * @param labs 格式化填充内容
     * @return 处理过返回描述的返回码对象
     */
    public ReturnCode formatDesc(Object... labs) {
        ReturnCode formatErrorCode = new ReturnCode(this.code, getFormatDesc(labs));
        return formatErrorCode;
    }

    /**
     * 将返回描述填充
     *
     * @param labs 格式化填充内容
     * @return 处理过的返回描述
     */
    public String getFormatDesc(Object... labs) {
        String[] infos = new String[labs.length];
        for (int i = 0; i < labs.length; i++) {
            //统一处理string
            infos[i] = String.valueOf(labs[i]);
        }
        return MessageFormat.format(desc, infos);
    }

    public String getSystem() {
        return system;
    }

    public String getCode() {
        return code;
    }

    public String getDesc() {
        if (desc != null && desc.length() > 0) {
            //替换沒使用的占位符
            return desc.replaceAll(regex, "");
        }
        return desc;
    }
}